<template>
  <div style="margin-left: 15px">
    <div
        style="position: fixed; z-index: 10; flex-direction: column; background: white; width: 100%; margin-top: -10px">
      <h1 class="header-text">用户信息管理</h1>

      <div class="search-bar">
        <el-input placeholder="输入ID/姓名 搜索用户" v-model="searchQuery" @input="handleInput"></el-input>
      </div>

      <div style="float:left;">
        <el-button type="primary" @click="handleAdd">新增用户
          <el-icon style="margin-left: 10px;">
            <CirclePlusFilled/>
          </el-icon>
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!multipleSelection.length">批量删除
          <el-icon style="margin-left: 10px;">
            <RemoveFilled/>
          </el-icon>
        </el-button>
      </div>

      <div style="float: right; margin-right: 100px">
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="currentPage"
                       :page-sizes="[10, 20, 50, 100]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="totalCount"/>
      </div>
    </div>

    <div class="table-container" style="margin-top: 10%;">
      <el-table :data="paginatedUsers" style="width: 100%" @selection-change="handleSelectionChange"
                @row-click="handleRowClick">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="uid" label="ID" style="width: 12.5%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.uid)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="uname" label="姓名" style="width: 12.5%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.uname)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="pswd" label="密码" style="width: 12.5%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.pswd)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" style="width: 12.5%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.email)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" style="width: 12.5%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.mobile)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建日期" style="width: 12.5%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.create_time)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="更新日期" style="width: 12.5%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.update_time)"></span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" size="small" @click.stop="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 用户信息模态框 -->
    <el-dialog :model-value="dialogVisible" title="用户信息" @close="dialogVisible = false">
      <el-form :model="selectedUser">
        <el-form-item label="ID">
          <el-input :disabled="isEdit" v-model="selectedUser.uid" autocomplete="off"
                    :class="{'is-error': uidExistError}" @input="checkUid"></el-input>
          <span class="error-message" v-if="uidExistError">该ID已使用，请重新输入！</span>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="selectedUser.uname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="selectedUser.pswd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="selectedUser.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="selectedUser.mobile" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-input v-model="selectedUser.create_time" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="更新日期">
          <el-input v-model="selectedUser.update_time" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm" v-if="!showButton">确认修改</el-button>
        <el-button type="primary" @click="addConfirm" v-if="showButton">确认添加</el-button>
      </template>
    </el-dialog>
  </div>
  <br class="fixed-container highlight">
</template>

<script>
import {ElMessage} from "element-plus";
import {CirclePlusFilled, RemoveFilled} from "@element-plus/icons-vue";
import UserAxiosService from "@/service/UserAPI.js"

export default {
  components: {
    RemoveFilled,
    CirclePlusFilled
  },
  data() {
    return {
      searchQuery      : '',
      paginatedUsers   : [],
      Users            : [], // 存储所有用户数据
      UsersUid         : [], // 存储ID数组
      showButton       : false,
      dialogVisible    : false,
      selectedUser     : {
        uid        : '',
        uname      : '',
        pswd       : '',
        email      : '',
        mobile     : '',
        create_time: '',
        update_time: '',
      },
      multipleSelection: [],
      uidExistError    : false, // ID已存在错误状态
      isEdit           : false, // 是否处于编辑模式
      originalUid      : '', // 原始ID，用于编辑时检查是否修改了ID
      currentPage      : 1, // 当前页码
      pageSize         : 10, // 每页显示条数
      totalCount       : 0, // 总条数
      size             : 'large', // 分页组件大小
    };
  },
  computed: {
    paginatedUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.Users.slice(start, end); // 返回分页后的用户数据
    }
  },
  methods : {
    handleInput() {
      this.paginatedUsers = this.Users.filter(user => {
        const searchString = `${user.uname} ${user.uid} ${user.mobile}`;
        return searchString.includes(this.searchQuery);
      }); // 更新分页后的用户数据
    },
    highlightMatch(text) {
      if (!this.searchQuery) return text;
      const regex = new RegExp(this.escapeRegExp(this.searchQuery), 'gi');
      return text.replace(regex, match => `<span style="color: #ff00f3;font-weight: bolder">${match}</span>`);
    },
    escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    },
    async handleDelete(index, row) {
      try {
        await UserAxiosService.deleteUser(row.uid); // 调用 API 删除用户
        this.Users.splice(index, 1); // 从用户列表中删除
        this.totalCount--; // 更新总条数
        this.$message({
          type   : 'success',
          message: '用户信息删除成功!'
        });
        await this.fetchUsers(); // 重新获取用户列表
      } catch (error) {
        console.error('Error deleting user:', error);
        this.$message({
          type   : 'error',
          message: '删除用户信息失败，请重试!'
        });
      }
    },
    async handleBatchDelete() {
      try {
        const deletePromises = this.multipleSelection.map(user => UserAxiosService.deleteUser(user.uid));
        await Promise.all(deletePromises);
        this.Users = this.Users.filter(user => !this.multipleSelection.includes(user)); // 更新用户列表
        this.totalCount -= this.multipleSelection.length; // 更新总条数
        this.multipleSelection = []; // 清空选中
        this.$message({
          type   : 'success',
          message: '批量删除成功!'
        });
        await this.fetchUsers(); // 重新获取用户列表
      } catch (error) {
        console.error('Error batch deleting users:', error);
        this.$message({
          type   : 'error',
          message: '批量删除失败，请重试!'
        });
      }
    },
    handleAdd() {
      this.showButton = true;
      this.isEdit = false;
      this.uidExistError = false;
      this.selectedUser = {
        uid        : '',
        uname      : '',
        pswd       : '',
        email      : '',
        mobile     : '',
        create_time: '',
        update_time: ''
      };
      this.dialogVisible = true; // 显示模态框
    },
    handleRowClick(row) {
      this.isEdit = true;
      this.originalUid = row.uid;
      this.selectedUser = {...row}; // 深拷贝用户数据
      this.dialogVisible = true; // 显示模态框
    },
    async handleConfirm() {
      try {
        await UserAxiosService.updateUser(this.selectedUser.uid, this.selectedUser); // 更新用户信息
        this.$message({
          type   : 'success',
          message: '用户信息更新成功!'
        });
        this.dialogVisible = false; // 关闭模态框
        await this.fetchUsers(); // 重新获取用户列表
      } catch (error) {
        this.$message({
          type   : 'error',
          message: '更新用户信息失败，请重试!'
        });
      }
    },
    async addConfirm() {
      if (!this.selectedUser.uid) {
        ElMessage.error("请输入ID！");
        return;
      }
      this.showButton = false;
      try {
        await UserAxiosService.addUser(this.selectedUser); // 添加新用户
        this.$message({
          type   : 'success',
          message: '用户信息添加成功!'
        });
        this.dialogVisible = false; // 关闭模态框
        await this.fetchUsers(); // 重新获取用户列表
      } catch (error) {
        this.$message({
          type   : 'error',
          message: '添加用户失败，请重试!'
        });
      }
    },
    async fetchUsers() {
      try {
        const data = await UserAxiosService.fetchAllUsers(); // 获取所有用户数据、
        console.log(data)
        this.Users = data; // 更新用户列表
        this.totalCount = data.length; // 更新总条数
        this.paginatedUsers = [...this.Users]; // 初始化分页用户
        this.UsersUid = this.Users.map(user => user.uid); // 存储所有用户ID
      } catch (error) {
        console.error('Error fetching users:', error);
      }
    },
    handleSizeChange(size) {
      this.pageSize = size; // 更新每页显示条数
      this.currentPage = 1; // 重置为第一页
    },
    handleCurrentChange(page) {
      this.currentPage = page; // 更新当前页码
    },
    async checkUid() {
      this.uidExistError = this.UsersUid.includes(this.selectedUser.uid) && this.originalUid !== this.selectedUser.uid; // 检查ID是否已存在
    },
    handleSelectionChange(val) {
      this.multipleSelection = val; // 更新选中的用户
    }
  },

  async created() {
    await this.fetchUsers(); // 组件创建时获取用户列表
  }
};
</script>

<style scoped>
.fixed-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  z-index: 999;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.error-message {
  color: red;
  font-size: 12px;
}

.highlight {
  color: red;
}

.search-bar {
  width: 95%;
  margin-bottom: 20px;
}

.header-text {
  background-clip: padding-box;
  display: flex;
  flex-direction: column;
  float: left;
  background: -webkit-linear-gradient(315deg, #3f9dfd 15%, #f36b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  color: transparent;
  font-weight: bolder;
}
</style>
